<template>
  <component 
    :is="drawer ? 'BaseDrawer' : 'BaseDialog'"
    :visible="visible"
    :title="title"
    :width="width"
    :size="size"
    :before-close="handleCancel"
    @cancel="handleCancel"
    @ok="handleOk"
    v-bind="dialogProps"
  >
    <Form
      ref="formRef"
      :labelWidth="$attrs.labelWidth || '80px'"
      :form-list="formList"
      :form-data="formValues"
      v-bind="$attrs"
      v-loading="loading"
    >
      <template
        v-for="name in Object.keys($scopedSlots)"
        #[name]="slotData"
      >
        <slot :name="name" v-bind="slotData"></slot>
      </template>
    </Form>
  </component>
</template>

<script>
import Form from '@/views/system/components/Form.vue';

export default {
  name: 'DialogForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    width: {
      type: String,
      default: "35%"
    },
    size: {
      type: [String,Number],
      default: "30%"
    },
    // 弹窗属性
    dialogProps: {
      type: Object,
      default: () => ({})
    },
    // 表单项
    formList: {
      type: Array,
      default: () => ([])
    },
    // 弹窗表单的初始值
    formData: {
      type: Object,
      default: () => ({})
    },
    // 提交表单
    onSubmit: {
      type: Function,
      default: () => new Promise((resolve) => resolve({})),
    },
    // 提交表单是否开启Loading
    isLoading: {
      type: Boolean,
      default: true
    },
    // 是否用 Drawer 替换 Dialog
    drawer: {
      type: Boolean,
      default: false
    },
  },
  components: {
    Form
  },
  data() {
    return {
      loading: false,
      formValues: {}
    };
  },
  watch: {
    formData: {
      handler(val) {
        this.formValues = {...val}
      },
      deep: true,
    }
  },
  mounted() {
    this.formValues = this.getInitialFormData()
  },
  methods: {
    getInitialFormData() {
      const obj = {};
      this.formList.forEach(item => {
        const { key, defaultValue = "" } = item;
        if (key) {
          obj[key] = defaultValue || "";
        }
      });
      return obj;
    },
    toggleLoading() {
      if (this.isLoading) {
        this.loading = !this.loading
      }
    },
    // 重置表单
    resetFields() {
      this.$refs.formRef.resetFields()
      this.formValues = this.getInitialFormData()
    },
    handleCancel() {
      this.$emit('cancel')
      this.resetFields()
    },
    handleOk() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          this.toggleLoading()
          const res = await this.onSubmit(this.formValues)
          if (res) {
            this.$emit('ok', res)
            this.resetFields()
          }
          this.toggleLoading()
        }
      });
    },
  },
}
</script>

<style>

</style>